package common;

import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

public class JwtToken {
	
	//公用密钥
	public static String SECRET = "jwttest";
	
	//创建token
	public static String createToken() {
		//生成（签发）时间
		Date iatDate = new Date();
		
		//过期时间 1min
		Calendar nowTime = Calendar.getInstance();
		nowTime.add(Calendar.MINUTE,1);
		Date expiresDate = nowTime.getTime();
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("alg", "HS256");
		map.put("typ", "JWT");
		String token = "";
		try {
			token = JWT.create()
							.withHeader(map)//header
							.withClaim("name", "JWT")//payload
							.withClaim("age", "3")
							.withClaim("org", "生成一个验证")
							.withExpiresAt(expiresDate)//过期时间，过期时间要大于签发时间
							.withIssuedAt(iatDate)//签名日期
							.sign(Algorithm.HMAC256(SECRET));//加密签名
		} catch (IllegalArgumentException | JWTCreationException | UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return token;
	}
	
	//解密token
	public static Map<String, Claim> verifyToken(String token) throws Exception{
		DecodedJWT jwt = null;
		JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
		try {
			jwt = jwtVerifier.verify(token);
		}catch (Exception e) {
		  throw new RuntimeException("token已过期，请重新验证！！");
		}
		return jwt.getClaims();
	}
	
	public static void main(String[] args) throws Exception {
		String token = createToken();
		System.out.println("生成的token：" + token);
		Map<String,Claim> claims = verifyToken(token);
		System.out.println(claims.get("name").asString());
		System.out.println(claims.get("age").asString());
		System.out.println(claims.get("org") == null ? "不存在org" : claims.get("org").asString());
		
		//过期后验证
		String expiresToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXV"
				+ "CJ9.eyJvcmciOiLnlJ_miJDkuIDkuKrpqozor4EiLCJuYW1lI"
				+ "joiSldUIiwiZXhwIjoxNTI3MTUzNDY5LCJpYXQiOjE1MjcxNTM0"
				+ "MDksImFnZSI6IjMifQ._23lNaPcRfcgKlU_WVpqL7CIr77IoEbp3oUpcmym5VI";
		Map<String,Claim> expiresClaims = verifyToken(expiresToken);
		
	}
}
